package com.etop.jansing.dao;

import com.etop.jansing.entities.Permission;
import com.etop.jansing.entities.ResourcePermission;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

/**
 * Created by jansing on 2015/10/26.
 */
@Repository
public class PermissionDao extends BaseDao<Permission> {

    public List<Permission> list() {
        return getSession().createQuery("from Permission p where p.valid=true")
                .list();
    }

    public List<Permission> getByIds(Collection<Long> ids) {
        return getSession().createQuery("from Permission p where p.id in (:ids) and p.valid=true")
                .setParameterList("ids", ids)
                .list();
    }

    public List<Permission> getByResourceId(long rid) {
        return getSession().createQuery("select p from ResourcePermission rp" +
                " left join rp.permission p" +
                " where rp.resource.id=:rid")
                .setLong("rid", rid)
                .list();
    }

    /**
     * 已被角色引用的权限
     *
     * @param id
     * @return
     */
    public List<Permission> getUsingPermission(long id) {
        return getSession().createQuery("select p from Role r" +
                " left join r.resourcePermissionList rp" +
                " left join rp.permission p" +
                " where r.valid=true and rp.resource.id=:id")
                .setLong("id", id)
                .list();
    }

    public Permission getByNameIgnoreValid(String name) {
        return (Permission) getSession().createQuery("from Permission p where p.valid=true and p.name=:name")
                .setString("name", name)
                .uniqueResult();
    }

    /**
     * 权限的使用情况
     *
     * @param permission
     * @return
     */
    public int isUsing(ResourcePermission resoPerm) {
        Session session = getSession();
        return session.createQuery("from Role r left join r.resourcePermissionList rp" +
                " where r.valid=true and rp.id=:id")
                .setLong("id", resoPerm.getId())
                .list()
                .size();
    }
}
